<template>
  <div class="app-container">
    <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
    <el-table :data="tableData" border highlight-current-row style="width: 100%; margin-top: 20px">
      <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
    </el-table>
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import enumerate from '@/enumerate'
import { batchAddStaffAPI } from '@/api'
import { formatExcelDate } from '@/utils'
export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: [],
      tableObj: enumerate.table
    }
  },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    async handleSuccess({ results, header }) {
      const newResults = []
      results.forEach((item) => {
        const res = {}
        // 拿到对象里所有key名
        const keyArr = Object.keys(item)
        keyArr.forEach((chKey) => {
          // 英文key名
          const enKey = this.tableObj[chKey]
          if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
            res[enKey] = formatExcelDate(item[chKey])
          } else {
            // 如果一个对象没有该属性，对象.属性=属性值 可以直接添加该属性
            res[enKey] = item[chKey]
          }
        })
        newResults.push(res)
      })
      console.log(newResults)
      this.tableData = results
      this.tableHeader = header
      // await只有成功才能执行下一行代码
      await this.batchAddStaff(newResults)
      this.$router.push('/employees')
    },
    // 批量导入员工
    async batchAddStaff(data) {
      await batchAddStaffAPI(data)
    }
  }
}
</script>
